const { body } = require('express-validator');
// const { User } = require('../model')
const md5 = require('../util/md5')
const db = require('../dbbase/db');
//用户验证
const validate = require('../middleware/validator')

exports.register = [
    validate([
        body('user.username').notEmpty().withMessage('用户名不能为空！'),
        body('user.password').notEmpty().withMessage('密码不能为空！'),
        body('user.usercode').notEmpty().withMessage('员工编号不能为空！'),
    ]),
    validate([
        body('user.usercode').custom( async usercode => {
            const sql = "select * from mov_app_users where usercode=:1";
            const params = [usercode];
            const user = await db.query(sql, params)
            if(user.length != 0){
                return Promise.reject(`员工编号${usercode}已存在`)
            }
        })
    ]),
    // validator([
    //     body('user.password').custom(async (password, { req }) => {
    //         const md5Password = md5(password);
    //         req.password = md5Password;
    //     })
    // ])
]

exports.login = [
    validate([
        body('user.username').notEmpty().withMessage('用户名不能为空！'),
        body('user.password').notEmpty().withMessage('密码不能为空！'),
        body('user.usercode').notEmpty().withMessage('员工编号不能为空！')
    ]),
    validate([
        body('user.usercode').custom( async (usercode,req ) => {
            const sql = "select * from mov_app_users where usercode=:1";
            const params = [usercode];
            const user = await db.query(sql, params);
            console.log(user);
            if(user.length == 0){
                return Promise.reject(`员工编号${usercode}不存在或还未注册`)
            }
            // body('user.username').custom((username) => {
            //     console.log(username);
            //     console.log(user[0].USERNAME);
            //     if (user[0].USERNAME != username) {
            //         return Promise.reject(`员工编号和用户名不匹配`)
            //     }
            // })
            //将数据挂载到req对象中，后边的中间件也可以使用
            req.user = user;
        })
    ]),
    
    // validator([
    //     body('user.username').custom(async (username, { req }) => {
    //         if (md5(password) != req.user.password) {
    //             return Promise.reject('密码错误！')
    //         }
    //     })
    // ])
   
]



